package com.yunhai.xc.common;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.yunhai.xc.common.ftp.FtpSingleton;

public class UploadUtil {
	public static String uploadFile(MultipartFile file) throws Exception {
		String uploadPath = "upload";
		int uid = 12;
		String attachLocation = "/opt/temp/";
		String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
		String originalFilename = file.getOriginalFilename();
		String extension = FilenameUtils.getExtension(originalFilename);
		// 保存的文件名 UUID.后缀
		String uuid = UUID.randomUUID().toString();
		String savedFilename = uuid + "." + extension;
		String dirInAttachDomain = String.format("%s/%s/%s", uploadPath, uid, dateStr);
		// 文件所在目录在磁盘里的全路径
		String dirInDisk = String.format("%s/%s", attachLocation, dirInAttachDomain);
		File dirPath = new File(dirInDisk);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		// 文件在磁盘中的全路径
		File fileToWrite = new File(String.format("%s/%s", dirInDisk, savedFilename));
		byte[] bytes = file.getBytes();
		FileCopyUtils.copy(bytes, fileToWrite);
		// 上传至ftp
		FtpSingleton.getInstance().upload(fileToWrite.getAbsolutePath());
		// 为了测试富文本编辑器暂时只返回文件名
		return savedFilename;
	}
}
